package com.example.demo.controller;

import com.example.demo.model.Classes;
import com.example.demo.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/classes")
@CrossOrigin(origins = "http://localhost:5173") // 允许前端访问
public class ClassController {
    @Autowired
    private ClassService classService;

    // 获取所有班级（支持分页和搜索）
    @GetMapping
    public Page<Classes> getAllClasses(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String graduationStatus) {
        
        // 如果提供了搜索条件，则执行搜索
        if ((name != null && !name.isEmpty()) || 
            (status != null && !status.isEmpty()) || 
            (graduationStatus != null && !graduationStatus.isEmpty())) {
            
            Classes.Status statusEnum = null;
            if (status != null && !status.isEmpty()) {
                try {
                    statusEnum = Classes.Status.valueOf(status);
                } catch (IllegalArgumentException e) {
                    // 如果状态值无效，则忽略状态搜索条件
                }
            }
            
            Classes.GraduationStatus graduationStatusEnum = null;
            if (graduationStatus != null && !graduationStatus.isEmpty()) {
                try {
                    graduationStatusEnum = Classes.GraduationStatus.valueOf(graduationStatus);
                } catch (IllegalArgumentException e) {
                    // 如果毕业状态值无效，则忽略毕业状态搜索条件
                }
            }
            
            return classService.searchClasses(name, statusEnum, graduationStatusEnum, page, size);
        } else {
            // 否则返回所有班级
            return classService.getAllClasses(page, size);
        }
    }

    // 根据ID获取班级
    @GetMapping("/{id}")
    public ResponseEntity<Classes> getClassById(@PathVariable Long id) {
        Optional<Classes> classes = classService.getClassById(id);
        if (classes.isPresent()) {
            return ResponseEntity.ok(classes.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建班级
    @PostMapping
    public Classes createClass(@RequestBody Classes classes) {
        return classService.saveClass(classes);
    }

    // 更新班级
    @PutMapping("/{id}")
    public ResponseEntity<Classes> updateClass(@PathVariable Long id, @RequestBody Classes classesDetails) {
        Optional<Classes> classes = classService.getClassById(id);
        if (classes.isPresent()) {
            Classes updatedClasses = classes.get();
            updatedClasses.setName(classesDetails.getName());
            updatedClasses.setCode(classesDetails.getCode());
            updatedClasses.setCollegeId(classesDetails.getCollegeId());
            updatedClasses.setMajorId(classesDetails.getMajorId());
            updatedClasses.setGrade(classesDetails.getGrade());
            updatedClasses.setSemester(classesDetails.getSemester());
            updatedClasses.setHeadTeacherId(classesDetails.getHeadTeacherId());
            updatedClasses.setStudentCount(classesDetails.getStudentCount());
            updatedClasses.setGraduationStatus(classesDetails.getGraduationStatus());
            updatedClasses.setStatus(classesDetails.getStatus());
            classService.saveClass(updatedClasses);
            return ResponseEntity.ok(updatedClasses);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除班级
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteClass(@PathVariable Long id) {
        Optional<Classes> classes = classService.getClassById(id);
        if (classes.isPresent()) {
            // 检查班级是否有关联的学生
            if (classService.hasStudents(id)) {
                return ResponseEntity.badRequest().body("无法删除班级，该班级下有关联的学生数据");
            }
            
            classService.deleteClass(id);
            return ResponseEntity.ok("班级删除成功");
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据名称搜索班级
    @GetMapping("/search")
    public List<Classes> searchClassesByName(@RequestParam String name) {
        return classService.getClassesByName(name);
    }

    // 根据专业ID获取班级（新增接口）
    @GetMapping("/major/{majorId}")
    public List<Classes> getClassesByMajorId(@PathVariable Long majorId) {
        return classService.getClassesByMajorId(majorId);
    }
}